#include "HelloJni.h"
#include <stdio.h>

JNIEXPORT jint JNICALL JNI_OnLoad
  (JavaVM *vm, void *reserved)
{
	JNIEnv* env = NULL;
	JNINativeMethod nm[2];
	jclass cls;
	jint result = -1;

	if ((*vm)->GetEnv(vm, (void*) &env, JNI_VERSION_1_4) != JNI_OK)
	{
		return JNI_ERR;
	}

	cls = (*env)->FindClass(env, "HelloJni");

	nm[0].name = "printHello";
	nm[0].signature = "()V";
	nm[0].fnPtr = (void*)Java_HelloJni_printHello;

	nm[1].name = "printString";
	nm[1].signature = "(Ljava/lang/String;)V";
	nm[1].fnPtr = (void*)Java_HelloJni_printString;

	(*env)->RegisterNatives(env, cls, nm, 2);

	return JNI_VERSION_1_4;
}

JNIEXPORT void JNICALL Java_HelloJni_printHello
  (JNIEnv * env, jobject obj)
{
	jclass cls = (*env)->GetObjectClass(env, obj);

	jfieldID tagID = (*env)->GetFieldID(env, cls, "tag", "Ljava/lang/String;");
	jmethodID printStringID = (*env)->GetMethodID(env, cls, "printString", "(Ljava/lang/String;)V");

	jstring tag = (jstring)((*env)->GetObjectField(env, obj, tagID));
	(*env)->CallVoidMethod(env, obj, printStringID, tag);
}

JNIEXPORT void JNICALL Java_HelloJni_printString
  (JNIEnv * env, jobject obj, jstring str)
{
	const jbyte * msg = (*env)->GetStringUTFChars(env, str, NULL);

	if(msg)
		printf("%s\n", msg);

	(*env)->ReleaseStringUTFChars(env, str, msg);
}

